<?php
namespace My\Controller;

use Utuo\BackgroundController;
use Utuo\Region;
use My\Model\AgentModel;
use My\Model\DistributionShopOrderModel;
use Utuo\UtuoModel;
use My\Model\DistributionShopModel;
use My\Model\WechatUserModel;
use My\Model\UserRole;

class AgentController extends BackgroundController {
	
	public $belong = array(
		'0' => '总商家',
		//'不定' => '已指定代理',
	);
	
	protected function _initialize() {
		$this->setControllerTitle('代理商管理');
		$this->setActionTitle(array(
				'index' => '代理商列表',
		        'add' => '添加代理商',
				'modify' => '修改代理商',
				'recycle' => '回收站' ,
		));
		$this->setActionNav(array(
				'index',
				'recycle'
		));
	}
	
	/**
	 * display the customer list
	 *
	 * @param unknown $is_deleted 是否已删除
	 */
	public function getLists($is_deleted) {
		$p = I("p", 1, 'intval');
		$pageSize = 10;
		/*查询条件*/
		$name = I('name', "");
		$level = I('level', "");
		$belong = I('belong', "");
		/*有条件查询*/
		$condition = array(
			"this0.is_deleted" => $is_deleted,
			"this0.cid" => $this->aid ,
		);
		$param = array();
		$name and $condition['this0.name'] = array('like', "%$name%") and $param['name'] = $name;
		$level!=='' and $condition['this0.level'] = array('eq', $level) and $param['level'] = $level;
		if ( $belong === '' ) {
			// 全部代理商
		} elseif( $belong == '0' ) {
			$param['belong'] = $condition["parent_id"] = 0; // 总厂商的直属代理
		} else {
			$agent = M("Agent")->where("cid=%d and id=%d", $this->aid, $belong)->find();
			$this->belong[$belong] = $agent['name'];
			$param['belong'] = $condition["parent_id"] = $belong*1; // 总厂商的直属代理
		}
		/*搜索*/
		$customerListSql = M()->table("__AGENT__ this0")->join('LEFT JOIN __CN_PROVINCE__ this1 on this0.province=this1.code')->join('LEFT JOIN __CN_CITY__ this2 on this0.city=this2.code')->join('LEFT JOIN __CN_AREA__ this3 on this0.area=this3.code')->field("this0.*,this1.name as provinceName,this2.name as cityName,this3.name as areaName")->select(false);
		$customerLists = M()->table($customerListSql . " this0")->where($condition)->limit($pageSize)->page($p)->order('id desc')->select();
		foreach ( $customerLists as &$v ) {
			$v['level'] = AgentModel::$agentLevel[$v['level']];
		}
		$count = M()->table($customerListSql . " this0")->where($condition)->count();
		$this->assign("agentTypeOptions", $this->getOption(AgentModel::$agentLevel, $param['level'], '==请选择代理等级=='));
		$this->assign("belongOptions", $this->getOption($this->belong, $param['belong'], '==全部代理商=='));
		$this->assign("agentLists", $customerLists);
		$this->assign("param", $param);
		$this->showPage($count, $pageSize, $param);
		$this->display();
	}
	
	/**
	 * 添加代理商信息
	 */
	public function addAction() {
		$agentId = I('wechat_uid', 0, "intval");
		$wechatUser = M("WechatUser")->where("cid=%d and id=%d", $this->aid, $agentId)->find();
		if ( $wechatUser ) {
			$partnerLists = M("Customer")->where('is_deleted=0')->getField('id,name');
			$agent['levelOptions'] = $this->getOption(AgentModel::$agentLevel, null, '==请选择代理等级==');
			$agent['provinceOptions'] = $this->getOption(Region::getProvinceList(), null, '==请选择省份==');
			$agent['cityOptions'] = $this->getOption(array(), null, '==请选择城市==');
			$agent['areaOptions'] = $this->getOption(array(), null, '==请选择地区==');
			$agent['locTypeOptions'] = $this->getOption(AgentModel::$locType, 0, '==请选择代理的区域性质==');
			$agent['wechat_uid'] = $agentId;
			$this->assign("agent", $agent);
			$this->display("save");
		} else {
			exit('请先选择已绑定此平台的微信用户');
		}
	}
	
	/**
	 * 修改代理商信息
	 */
	public function modifyAction() {
	    $model = CONTROLLER_NAME;
	    $agent = D($model)->getOneById();
	    $agent['levelOptions'] = $this->getOption(AgentModel::$agentLevel, $agent['level'], '==请选择代理等级==');
		$agent['provinceOptions'] = $this->getOption(Region::getProvinceList(), $agent['province'], '==请选择省份==');
		$agent['cityOptions'] = $this->getOption(Region::getCityListByProvince($agent['province']), $agent['city'], '==请选择城市==');
		$agent['areaOptions'] = $this->getOption(Region::getAreaListByCity($agent['city']), $agent['area'], '==请选择地区==');
		$agent['locTypeOptions'] = $this->getOption(AgentModel::$locType, $agent['is_loc_type'], '==请选择代理的区域性质==');
	    $this->assign(lcfirst($model), $agent);
	    $this->display("save");
	}
	
	/**
	 * ajax返回代理商列表
	 */
	public function getAgentListAction() {
		$name = I("name", "");
		$userList = M("Agent")->where(array('_complex' => array("name"=>array("like", "%".$name."%"),
                        										"email"=>array("like", "%".$name."%"),
		                                                        "tel"=>array("like", "%".$name."%"),
                        										"_logic" => 'or') ,
										"status"=>1, "is_deleted"=>0,
										"cid" => $this->aid,
									 ))
							 ->field('id,email,name,tel')->select();
		$this->ajaxSuccess("", $userList);
	}
	
	/**
	 * 删除代理商
	 */
	public function deleteAction() {
		$id = I("id", 0, "intval");
		/** 搜集信息 */
		/* 搜集未处理的订单 */
		$condition = array(
			'cid' => $this->aid,
			'id' => $id,
			'order_status' => array('not in', array(DistributionShopOrderModel::ORDER_STATUS_CANCELED, DistributionShopOrderModel::ORDER_STATUS_COMPLETED) ),
		);
		$count = M("DistributionShopOrder")->where($condition)->count();
		if ( $count > 0 ) {
			$this->ajaxError('代理商存在未处理的订单，请处理完所有订单再重试本操作.');
		}
		/* 搜集未派发的盈余 */
		$count = M("DistributionShopOrderSettleAccounts")->where("end_agent=%d and status=0", $id)->count();
		if ( $count > 0 ) {
			$this->ajaxError('代理商存在未处理的资金结算，请处理完所有资金结算重试本操作.');
		}
		$agent = M("Agent")->where("id=%d", $id)->find();
		isset($agent['id']) and $ids = array( $agent['id'] );
		$level = 0;
		while ( $ids and $agentLists = M("Agent")->where( array('parent_id' => array('in', $ids)) )->select() ) {
			$ids = array();
			$update = array();
			foreach ( $agentLists as $v ) {
				$ids[] = $v['id'];
				$update[$v['id']] = array(
					'tree' => trim( preg_replace('/\,?[^\d]'.$agent['id'].'\,?/', ',', $v['tree']), "," ),
				);
				$level===0 and $update[$v['id']]['parent_id'] = $agent['parent_id'];
			}
			$update and M("Agent")->where(array('id'=>array('in', array_keys($update))))->save(UtuoModel::batchUpdateData($update));
			$level++;
		}
		if ( false !== M("Agent")->where("id=%d", $id)->delete() ) {
			M("AgentAdmin")->where('agent_id=%d', $id)->delete();
			$userRole = new UserRole();
			$wechatUser = M("WechatUser")->where('id=%d and cid=%d', $agent['wechat_uid'], $agent['cid'])->find();
			$type = $userRole->type($wechatUser['type'])->clearTo(WechatUserModel::USER_TYPE_AGENT)->getType();
			M("WechatUser")->where('id=%d and cid=%d', $agent['wechat_uid'], $agent['cid'])->setField( 'type', $type );
			$this->ajaxSuccess("删除成功!");
		}
		$this->ajaxError("删除失败");
	}
	
	/**
	 * 获取城市
	 */
	public function getCityPostAction() {
		echo $this->getOption(Region::getCityListByProvince(I('code')), '', '==请选择城市==');
	}
	
	/**
	 * 获取地区
	 */
	public function getAreaPostAction() {
		echo $this->getOption(Region::getAreaListByCity(I('code')), '', '==请选择地区==');
	}
	
	// 提交修改菜单
	public function submitPost($model) {
	    $model = is_object($model) ? $model : D($model);
	    if ($model->isCreated or $model->create()) {
	        if (empty($_REQUEST['id'])) {
	            unset($model->id);
	            // $authField = C("AUTH_FIELD") and $model->$authField = $this->aid;
	            $model->parentId = $this->getParentId();
	            if ($model->add()) {
	                $this->ajaxSuccess("添加成功！");
	            } else {
	                $this->ajaxError("添加失败！");
	            }
	        } else {
	            $model->parentId = $this->getParentId();
	            if (false !== $model->save()) {
	                $this->ajaxSuccess("修改成功！");
	            } else {
	                $this->ajaxError("修改失败！");
	            }
	        }
	    } else {
	        $this->ajaxError($model->getError());
	    }
	}
	
	/**
	 * 获得代理推荐人
	 * @return number
	 */
	private function getParentId() {
	    /* 父级代理 */
	    $parentId = $_REQUEST['parent_id']*1 ;
	    $level = $_REQUEST['level']*1 ;
	    if ( $parentId*1 ) {
	        $agent = M("Agent")->where("id=%d", $parentId)->find();
	        if ( $agent ) {
	            //$agent['level'] >= $level and $this->ajaxError("推荐代理商设置错误，推荐代理商等级必须高于新加的代理等级");
	        } else {
	            $parentId = 0;
	        }
	    }
	    return $parentId;
	}
	
}